<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use util\Excel;
use util\Upload;

/**
 * Purchasedcg控制器
 */
class Purchasedcg extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Purchase();

        $this->validate = \app\admin\validate\Purchase::class;
    }

    public function index()
    {

        list($limit, $where, $sortArr) = $this->buildTableParames();
        $where[] = ['merge_status', 'in', [2, 3]];
        $list = $this->model
            ->field("id,brand,SUM(`num`) as num,admin_id,product_id,apply_status,apply_type,union_batch,order_num,purchase_time")
            ->where($where)
            ->where([$where])
            ->order('apply_time desc')
            ->group('union_batch')
            ->paginate($limit);

        $lists = $list->items();
        foreach ($lists as $k => $v) {
            //查询id
            $day = table('product')
                ->where(['id' => $v['product_id']])->find();
            if (!empty($day)) {
                $sum = $day['arrive_day'];
            } else {
                $sum = 0;
            }
            //查询purchase表的id
            $purchase_info = table('purchase')->where(['union_batch' => $v['union_batch']])->select()->toarray();

            $batch_info = table('dcg')->where(['union_batch' => $v['union_batch']])->find();
            $lists[$k]['arrive_day'] = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('m'), date('d') + $sum, date('Y')));
            $lists[$k]['order_num'] = !empty($batch_info) ? array_column($batch_info, 'order_num') : 0;
            if (!empty($lists[$k]['order_num'])) {
                $lists[$k]['order_num'] = implode(',', $lists[$k]['order_num']);
            }
            $lists[$k]['real_num'] =  !empty($batch_info['real_num']) ? $batch_info['real_num'] : 0;
            $lists[$k]['purchase_price'] = !empty($batch_info['purchase_price']) ? $batch_info['purchase_price'] : 0;
            $lists[$k]['draft'] =  $v['apply_status'] == 5 ? '草稿' : '待采购';
            //物流单号
            $lists[$k]['wl_num'] = !empty($batch_info['wl_num']) ? $batch_info['wl_num'] : 0;
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list->items(),
        ];
        return json($data);
    }

    //待采购数据数据操作
    public function edit_number()
    {
        $post = $this->request->post();
        //是否保存草稿
        if (isset($post['is_draft']) && $post['is_draft']) {
            $is_draft = 1;
        } else {
            $is_draft = 0;
        }
        $id = !empty($post['id']) ? $post['id'] : 0;
        //采购信息
        $purchase_info  = table('purchase')->where(['id' => $id])->find();
        //审核合并之后的批次号
        $union_batch = !empty($purchase_info['union_batch']) ? $purchase_info['union_batch'] : '';
        $dcg_info = table('dcg')->where(['union_batch' => $union_batch])->find();
        $purchase_data = table('purchase')->field('id,sku,color,num,real_num')->where(['union_batch' => $union_batch])->select()->toarray();
        if (empty($dcg_info)) {
            //插入
            $data = [
                'order_num' => $post['order_num'],
                'union_batch' => $union_batch,
                'purchase_price' => $post['purchase_price'],
                'wl_num' => $post['wl_num'],
                'real_num' => $post['real_num'],
                'sum_num' => $post['sum_num'],
                'addtime' => date('Y-m-d H:i:s'),
            ];
            table('dcg')->where(['union_batch' => $post['union_batch']])->insert($data);
            //更新对应的数量
            foreach ($purchase_data as $key => $value) {
                table('purchase')->where(['id' => $value['id']])->update(['real_num' => $value['real_num'], 'real_num_correct' => $value['real_num']]);
            }
            $dcg_info = table('dcg')->where(['union_batch' => $union_batch])->find();
        }
        if (!empty($dcg_info) && count($post) > 1) {
            //回显数据
            if ($post['display'] == 1) {
                $msg = '回显数据';
                //物流单号
                if (!empty($dcg_info['wl_num'])) {
                    $dcg_info['wl_num'] = explode(',', $dcg_info['wl_num']);
                } else {
                    $dcg_info['wl_num'] = [];
                }
                //1688单号
                if (!empty($dcg_info['order_num'])) {
                    $dcg_info['order_num'] = explode(',', $dcg_info['order_num']);
                } else {
                    $dcg_info['order_num'] = [];
                }
                foreach ($purchase_data as $k => $v) {
                    $purchase_data[$k]['sku'] = $v['color'] . '-' . $v['sku'];
                    $purchase_data[$k]['editname'] = false;
                    $purchase_data[$k]['num'] = (int)$v['num'];
                    $purchase_data[$k]['real_num'] = (int)$v['real_num'];
                }
            } else {
                $msg = '更新数据';
                //通过union_batch查询所有待采和部分待采的数据
                $sj_num = table('purchase')->where(['union_batch' => $post['union_batch']])->sum('num');
                if ($sj_num < $post['real_num']) {
                    $merge_status = 4;
                } else {
                    $merge_status = 5;
                }
                //更新数据
                if (!empty($post['wl_num'])) {
                    $post['wl_num'] = implode(',', $post['wl_num']);
                } else {
                    $post['wl_num'] = '';
                }
                if (!empty($post['order_num'])) {
                    $post['order_num'] = implode(',', $post['order_num']);
                } else {
                    $post['order_num'] = '';
                }
                if (!empty($post['purchase_data'])) {
                    $draft = $is_draft == 0 ? 4 : 5;
                    foreach ($post['purchase_data'] as $k => $value) {
                        table('purchase')->where(['id' => $value['id']])->update(['real_num' => $value['real_num'], 'real_num_correct' => $value['real_num'], 'apply_status' => $draft, 'merge_status' => $merge_status]);
                    }
                }
                $data = [
                    'order_num' => $post['order_num'],
                    'purchase_price' => $post['purchase_price'],
                    'wl_num' => $post['wl_num'],
                    'real_num' => $post['real_num'],
                    'sum_num' => $post['sum_num'],
                ];
                table('dcg')->where(['union_batch' => $post['union_batch']])->update($data);
                // foreach ($purchase_data as $key => $value) {
                //     table('purchase')->where(['id' => $value['id']])->update(['real_num' => $value['real_num'], 'apply_status' => 4]);
                // }
            }
            $data2['purchase_data'] = $purchase_data;
            $data2['dcg_info'] = $dcg_info;
            $data2['id'] = $id;
            $data2['msg'] = $msg;
            return success('操作成功', $data2);
        } else {
            $data = [
                'code' => 1,
                'msg' => '显示数据',
                'data' => $dcg_info,
                'purchase_data' => $purchase_data,
                'id' => $id,
            ];
            return json($data);
        }
    }

    // //添加物流单号
    // public function edit_wlnumber()
    // {

    //     $post = $this->request->post();
    //     $id = !empty($post['id']) ? $post['id'] : 0;
    //     //采购信息
    //     $purchase_info  = table('purchase')->where(['id' => $id])->find();
    //     //合并之后的批次号
    //     $union_batch = !empty($purchase_info['union_batch']) ? $purchase_info['union_batch'] : '';
    //     $wl_info = table('wldh')->where(['union_batch' => $union_batch])->select()->toarray();
    //     if (empty($wl_info)) {
    //         table('wldh')->insertAll($post);
    //         $return = [
    //             'id' => $id,
    //             'union_batch' => $post['union_batch'],
    //         ];
    //         return success('操作成功', $return);
    //     } elseif (!empty($dcg_info) && count($post) > 1) {
    //         //更新
    //         $data = [
    //             'order_num' => $post['order_num'],
    //             'purchase_price' => $post['purchase_price'],
    //         ];
    //         table('wldh')->where(['union_batch' => $post['union_batch']])->updateAll($data);
    //         return success('操作成功', $wl_info);
    //     } else {
    //         $data = [
    //             'code' => 1,
    //             'msg' => '',
    //             'data' => $wl_info,
    //         ];
    //         return json($data);
    //     }
    // }

    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $union_batch = !empty($post['union_batch']) ? $post['union_batch'] : 0;
            $remarks = !empty($post['remarks']) ? $post['remarks'] : 0;
            $where[] = ['merge_status', 'in', [2, 3]];
            table('purchase')->where($where)->where(['union_batch' => $union_batch])->update(['merge_status' => 9, 'remarks' => $remarks]);
            return success('操作成功');
        }
        return success('ok', $row);
    }


    /**
     * 导出
     */
    public function export()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $fields = $this->request->get('fields');
        $fields = json_decode($fields, true);

        $header = [];
        foreach ($fields as $vo) {
            $header[] = [$vo['comment'], $vo['field']];
        }

        $tableIds = $this->request->get('tableIds');
        $tableIds = is_array($tableIds) ? $tableIds : explode(',', $tableIds);
        $where[] = ['id', 'in', $tableIds];

        $tableName = $this->model->getName();
        $lists = $this->model
            ->field("id,brand,SUM(`num`) as num,admin_id,product_id,apply_status,apply_type,union_batch,order_num")
            ->where($where)
            ->where(['apply_status' => 2])
            ->order('apply_time desc')
            ->group('union_batch')
            ->limit(100000)
            ->select()
            ->toArray();
        foreach ($lists as $k => $v) {
            //查询id
            $day = table('product')
                ->where(['id' => $v['product_id']])->find();
            if (!empty($day)) {
                $sum = $day['arrive_day'];
            } else {
                $sum = 0;
            }
            $batch_info = table('dcg')->where(['union_batch' => $v['union_batch']])->find();
            $lists[$k]['arrive_day'] = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('m'), date('d') + $sum, date('Y')));
            $lists[$k]['order_num'] = !empty($batch_info['order_num']) ? $batch_info['order_num'] : 0;
            $lists[$k]['real_num'] =  !empty($batch_info['real_num']) ? $batch_info['real_num'] : 0;
            $lists[$k]['purchase_price'] = !empty($batch_info['purchase_price']) ? $batch_info['purchase_price'] : 0;
        }
        $fileName = "export_" . $tableName . "_" . time();
        // halt($header);
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    /**
     * 导出
     */
    public function export_number()
    {
        $id = $this->request->get('id');
        $purchase_info  = table('purchase')->where(['id' => $id])->find();
        $union_batch = !empty($purchase_info['union_batch']) ? $purchase_info['union_batch'] : '';
        $lists = array();
        if (!empty($union_batch)) {
            $lists = table('purchase')->field('id,sku,color,num,real_num,brand')->where(['union_batch' => $union_batch])->select()->toarray();
        }
        $real_num = 0;
        $num = 0;
        foreach ($lists as $k => $v) {
            $lists[$k]['union_batch'] = $union_batch;
            $lists[$k]['sku'] = $v['color'] . '-' . $v['sku'];
            $real_num += $v['real_num'];
            $num += $v['num'];
        }
        $num1 = [];
        $num1['id'] = '总计';
        $num1['union_batch'] = '';
        $num1['sku'] = '';
        $num1['num'] = $num;
        $num1['brand'] = '';
        $num1['real_num'] = $real_num;
        $lists[] = $num1;
        $tableName = $this->model->getName();

        $header = array();
        $header[] = ['ID', 'id'];
        $header[] = ['批次号', 'union_batch'];
        $header[] = ['编号', 'brand'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['待采数量', 'num'];
        $header[] = ['实际已采数量', 'real_num'];

        $fileName = "export_" . $tableName . "_" . time();
        // halt($header);
        return Excel::exportData($lists, $header, $fileName, 'xls');
    }


    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_cost($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }

    //导入花费
    public function import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        foreach ($data as  $value) {
            if (isset($value[0]) && !empty($value[0]) && isset($value[5])) {
                $purchase = array();
                $purchase['real_num'] = $value[5];
                table('purchase')
                    ->where('id', $value[0])
                    ->update($purchase);
            }
        }
        return $url;
    }
}
